package com.nymph.executor.statement;

import com.nymph.mapping.MappedStatement;
import com.nymph.util.CommonUtis;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: This is a sample class.
 * @Author: Simon
 */
public class SimpleStatementHandler implements StatementHandler{
    // 正则
    private static Pattern param_pattern = Pattern.compile("#\\{([^\\{\\}]*)\\}");

    private MappedStatement mappedStatement;

    public SimpleStatementHandler(MappedStatement ms){
        this.mappedStatement=ms;
    }
    @Override
    public PreparedStatement prepare(Connection paramConnection) throws SQLException {
        String originalSql = mappedStatement.getSql();
        if (CommonUtis.isNotEmpty(originalSql)){
            return paramConnection.prepareStatement(parseSymbol(originalSql));
        }else{
            throw new SQLException("original sql is null");
        }
    }

    @Override
    public ResultSet query(PreparedStatement preparedStatement) throws SQLException {
        return preparedStatement.executeQuery();
    }

    @Override
    public void update(PreparedStatement preparedStatement) throws SQLException {
        preparedStatement.executeUpdate();
    }

    // 提前处理{}防止sql注入
    private static String parseSymbol(String source){
        source=source.trim();
        Matcher matcher=param_pattern.matcher(source);
        return matcher.replaceAll("?");
    }
}
